<template>
  <div>
    <div>
      <!-- 答案信息表单 -->
      <FormPanel ref="formPanel" :list="formList" formType="add" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <!-- 选项信息表格 -->
      <FilterTable
        ref="table"
        :columns="answerColumns"
        :dataSource="answerList"
        :isSelectColumn="false"
        :height="'auto'"
        columnsRef="wjdyDaxzXxxxTable"
        :onSyncTableData="syncTableFun"
        :onColumnsChange="columns => (this.answerColumns = columns)"
      >
        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addAnswer()">新增选项</el-button>
        </template>
      </FilterTable>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDrawer(false)">取 消</el-button>
      <el-button type="primary" :loading="loginBtnState" @click="commit">提 交</el-button>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/customerRepair/visitRules/questionnaireMake2/types';
import moment from 'moment';
import { getAnswerEditInfo, saveAnswerInfo, editAnswerInfo, queryAnswersPagByIds } from '@/api/customerRepair/visitRules/questionnaireMake2';
import { dictionary } from '@/utils/dictMixin';

export default {
  name: 'AnswerPanel',
  mixins: [dictionary],
  props: {
    answerGroupId: String,
    type: String
  },
  data() {
    this.BaseTable = null;
    return {
      formList: this.createFormList(), // 答案表单
      answerList: [], // 选项数据表格
      answerColumns: this.createAnswerColumns() // 选项表格列
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    loginBtnState() {
      return this.btnLoading[types.SAVE];
    }
  },
  created() {
    this.getAnswer();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // 获取答案信息
    async getAnswer() {
      if (this.answerGroupId) {
        const res = await getAnswerEditInfo(this.answerGroupId);
        if (res.resultCode == 200) {
          this.answer = res.data;
          this.answerList = res.data.answerList;
        } else {
          this.$message.error('获取答案信息失败');
          return;
        }
      } else {
        this.answer = {
          answerGroupName: '',
          answerGroupDescript: '',
          isValid: 10041001,
          dataSources: 10451001
        };
        this.answerList = [];
      }
      this.formList[0].initialValue = this.answer.answerGroupName;
      this.formList[1].initialValue = this.answer.answerGroupDescript;
      this.formList[2].initialValue = this.answer.isValid;
      this.formList[3].initialValue = this.answer.dataSources;
      this.formList = [...this.formList];
      this.answerList = [...this.answerList];
    },
    // 创建表单列
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '答案名称',
          fieldName: 'answerGroupName',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请填写答案名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '答案说明',
          fieldName: 'answerGroupDescript',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请填写答案说明', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'isValid',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSources',
          itemList: this.createDictList('1045'),
          disabled: true
        }
      ];
    },
    // 选项表格列
    createAnswerColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.answerId ? true : false} onClick={() => this.delAnswer(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '选项内容',
          dataIndex: 'answer',
          filterType: 'input',
          showOverflowTooltip: true,
          editable: true,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写选项内容', trigger: 'blur' }],
          defaultEditable: true
        },
        {
          title: '排列顺序',
          dataIndex: 'answerSort',
          filterType: 'input',
          editable: true,
          editType: 'input',
          editRequired: true,
          editPattern: /^[0-9]+$/,
          rules: [{ required: true, message: '请填写排列顺序', trigger: 'blur' }],
          defaultEditable: true
        }
      ];
    },
    // 监听表格数据
    syncTableFun(val) {
      if (val && val.length > 0) {
        for (const obj of val) {
          // 如果有id不让编辑
          if (obj.answerId) {
            this.BaseTable.SET_CELL_DISABLED(obj, 'column-action', true);
            this.BaseTable.SET_CELL_DISABLED(obj, 'answer', true);
          }
        }
      }
    },
    // 关闭
    closeDrawer(refresh) {
      if (refresh) {
        this.$emit('changeHandle', { dataSources: 10451001 });
      }
      this.$emit('close', false);
    },
    // 新增选项
    addAnswer() {
      let answer = {
        answer: '',
        answerSort: ''
      };
      this.answerList.push(answer);
    },
    // 删除选项
    delAnswer(row) {
      if (this.answerList.length === 1) {
        this.$message.info('请保留至少一个选项信息');
        return;
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 有answerId，直接真删，再从answerList中移除
          if (row.answerId) {
            delAnswerById(row.answerId).then(res => {
              if (res.resultCode == 200) {
                this.answerList.splice(row.$index, 1);
              } else {
                this.$message.error('删除失败');
              }
            });
          } else {
            // 没有ANSWER_ID，直接从answerList中移除
            this.answerList.splice(row.$index, 1);
          }
        })
        .catch(() => {});
    },
    // 点击提交
    commit() {
      // 调用表单验证
      this.$refs.formPanel.SUBMIT_FORM();
    },
    // 表单验证回调，传回表单参数
    formChangeHandle(val) {
      // 检验是否添加选项信息
      if (this.answerList.length === 0) {
        this.$message.info('请添加选项信息');
        return;
      }
      let a = true;
      let answerSortArr = [];
      // 检验选项信息是否正确
      for (let i = 0; i < this.answerList.length; i++) {
        if (this.answerList[i].answer == '' || this.answerList[i].answer == null || this.answerList[i].answer == undefined) {
          this.$message({
            type: 'error',
            message: '选项内容不能为空!'
          });
          a = false;
          break;
        }
        if (this.answerList[i].answerSort == '' || this.answerList[i].answerSort == null || this.answerList[i].answerSort == undefined) {
          this.$message({
            type: 'error',
            message: '排列顺序不能为空!'
          });
          a = false;
          break;
        }
        if (answerSortArr.indexOf(parseInt(this.answerList[i].answerSort)) != -1) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行排列顺序不能重复!'
          });
          a = false;
          break;
        }
        answerSortArr.push(parseInt(this.answerList[i].answerSort));
      }
      if (a) {
        // 提交保存
        this.answer.answerGroupName = val.answerGroupName;
        this.answer.answerGroupDescript = val.answerGroupDescript;
        this.answer.dataSources = val.dataSources;
        this.answer.isValid = val.isValid;
        this.answer.answerList = this.answerList;
        saveAnswerInfo(this.answer).then(res => {
          if (res.resultCode === 200) {
            this.$message.success('保存成功');
            this.closeDrawer(true);
          } else {
            this.$message.error('保存失败');
          }
        });
      }
    }
  }
};
</script>
